//
//  BigPhotoView.m
//  HotMumTest
//
//  Created by 杨 敏 on 13-5-21.
//  Copyright (c) 2013年 Yang Min. All rights reserved.
//

#import "BigPhotoView.h"
#import "ConstantHeader.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "Tool.h"

@interface BigPhotoView()<UIGestureRecognizerDelegate,UIScrollViewDelegate,SDWebImageManagerDelegate>
{
   // CGFloat lastScale;
    BOOL animating;
}
@property(nonatomic,assign)CGRect originalFrame;
@property(nonatomic,strong)UIScrollView *scroll;
@property(nonatomic,strong)UITapGestureRecognizer *singletTapGesture;
@property(nonatomic,strong)UITapGestureRecognizer *doubleTaoGesture;
@property(nonatomic,strong)UIActivityIndicatorView *spinner;

@end

@implementation BigPhotoView

#pragma mark - life
-(void)dealloc{
    [_photoV cancelCurrentImageLoad];
    
}
-(void)willMoveToWindow:(UIWindow *)newWindow{
    [super willMoveToWindow:newWindow];
//    if (!newWindow) {
//        ApplicationDelegate.leftSwipeGesture.enabled=YES;
//    }
//    else{
//        ApplicationDelegate.leftSwipeGesture.enabled=NO;
//    }
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
                
        self.scroll = [[UIScrollView alloc] initWithFrame:frame];
        _scroll.backgroundColor = [UIColor clearColor];
        _scroll.delegate = self;
        _scroll.bounces = YES;
        _scroll.minimumZoomScale = 1.0;
        _scroll.maximumZoomScale = 2.0;
        [self addSubview: _scroll];
     
        self.doubleTaoGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTapped:)];
        _doubleTaoGesture.numberOfTapsRequired=2;
        [_scroll addGestureRecognizer:_doubleTaoGesture];
        
        self.singletTapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTapped:)];
        _singletTapGesture.numberOfTapsRequired=1;
        [_scroll addGestureRecognizer:_singletTapGesture];
        
        [_singletTapGesture requireGestureRecognizerToFail:_doubleTaoGesture];
        
        
        self.photoV=[[IndicatorImageView alloc]initWithFrame:self.bounds];
        _photoV.contentMode=UIViewContentModeScaleAspectFill;
        _photoV.clipsToBounds=YES;

        _scroll.contentSize = _photoV.frame.size;
        [_scroll addSubview:_photoV];

    }
    return self;
}

#pragma mark - Public

-(void)fillWithOriginalFrame:(CGRect)originalFrame thumbUrl:(NSURL *)thumbUrl fullUrl:(NSURL *)fullUrl width:(CGFloat)width height:(CGFloat)height{
    
    //ApplicationDelegate.leftSwipeGesture.enabled=NO;
    
    NSLog(@"thumbUrl:%@,fullUrl:%@,originalFrame:%@,width:%f,height:%f",thumbUrl,fullUrl,NSStringFromCGRect(originalFrame),width,height);
    if ([thumbUrl isEqual:fullUrl]) {
        thumbUrl=nil;
    }
    
    _photoV.frame=originalFrame;
    _originalFrame=originalFrame;
    
    __weak typeof(self) wself = self;

    if (thumbUrl) {
        CGRect targetImgFrame =[self getScaleFrameWithWidth:width height:height];
        CGPoint scrollOffset=[self getScrollCenterOffSetWithPhotoSize:targetImgFrame.size];

        [_spinner startAnimating];
        [_photoV setImageWithURL:thumbUrl completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
            NSLog(@"image.size:%@",NSStringFromCGSize(image.size));

            [wself.spinner stopAnimating];
            [wself setMaxMinZoomScale];
            
            animating=YES;
            
            [UIView animateWithDuration:0.3 animations:^{
                wself.alpha=1;
                
                wself.photoV.frame=targetImgFrame;
                [wself.scroll setContentOffset:scrollOffset animated:NO];
                
            } completion:^(BOOL finished) {
                animating=NO;
                
                [wself.scroll setZoomScale:wself.scroll.minimumZoomScale animated:NO];
                
                if (fullUrl) {
                    [wself.photoV setImageWithURL:fullUrl placeholderImage:wself.photoV.image completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                        NSLog(@"image.size:%@",NSStringFromCGSize(image.size));
                        [wself.spinner stopAnimating];
                        [wself setMaxMinZoomScale];
                    }];
                }
            }];
        }];
    }
    else if (fullUrl) {
        [_spinner startAnimating];
        [_photoV setImageWithURL:fullUrl placeholderImage:_photoV.image completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
            NSLog(@"image.size:%@",NSStringFromCGSize(image.size));

            [wself fullImageDidFinished:image];
        }];
    }
}
-(void)fullImageDidFinished:(UIImage *)image{
    [_spinner stopAnimating];
    [self setMaxMinZoomScale];
    
    CGRect targetImgFrame =[self getScaleFrameWithWidth:image.size.width height:image.size.height];
    CGPoint scrollOffset=[self getScrollCenterOffSetWithPhotoSize:targetImgFrame.size];
    
    
    animating=YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha=1;
        
        _photoV.frame=targetImgFrame;
        
        [_scroll setContentOffset:scrollOffset animated:NO];
        
        
    }completion:^(BOOL finished) {
        animating=NO;
        
        [_scroll setZoomScale:_scroll.minimumZoomScale animated:NO];
    }];

}
#pragma mark - Action
-(void)singleTapped:(UITapGestureRecognizer *)gesture{
    //DLog(@"");
    [self dismiss];
}
-(void)doubleTapped:(UITapGestureRecognizer *)gesture{
   // DLog(@"");
    CGPoint point = [gesture locationInView:_photoV];
    //[_scroll setZoomScale:_scroll.zoomScale==_scroll.maximumZoomScale?_scroll.minimumZoomScale:_scroll.maximumZoomScale animated:YES];
    [self handleDoubleTap:point];
}

- (void)handleDoubleTap:(CGPoint)touchPoint {
	if (_scroll.zoomScale == _scroll.maximumZoomScale) {
		
		[_scroll setZoomScale:_scroll.minimumZoomScale animated:YES];
		
	} else {
		
		[_scroll zoomToRect:CGRectMake(touchPoint.x, touchPoint.y, 1, 1) animated:YES];
	}
}
-(void)dismiss{
    _singletTapGesture.enabled=NO;
    _doubleTaoGesture.enabled=NO;
    
    [_photoV cancelCurrentImageLoad];
    
    CGFloat zoom = [_scroll zoomScale];

    animating=YES;
    //[[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];

    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        [_scroll setContentOffset:CGPointZero animated:NO];

        if (zoom==1.0) {
            _photoV.frame=_originalFrame;
        }
        else{
            //_originalFrame.origin.x+=scrollView.contentOffset.x;
            //_originalFrame.origin.y+=scrollView.contentOffset.y;
            
            _photoV.frame=_originalFrame;
        }

    } completion:^(BOOL finished) {
        self.alpha=0;
        animating=NO;
        [self removeFromSuperview];
        
        //ApplicationDelegate.leftSwipeGesture.enabled=YES;
    }];

}


#pragma mark - LayOut
- (void)layoutSubviews {
	if (!_spinner.hidden){
        _spinner.center = CGPointMake(floorf(_scroll.frame.size.width/2.0),
                                      floorf(_scroll.frame.size.height/2.0));
    }
	[super layoutSubviews];
}
- (void)setMaxMinZoomScale{
    CGSize imgSize =[_photoV image].size;
    
    CGSize boundsSize = _scroll.bounds.size;

    CGFloat maxScale=MAX(imgSize.width/boundsSize.width, imgSize.height/boundsSize.height);
    
    _scroll.maximumZoomScale =MAX(2.0, maxScale);
  //  _scroll.zoomScale=_scroll.minimumZoomScale;
    
}
-(CGPoint)getScrollCenterOffSetWithPhotoSize:(CGSize)photoSize{
    CGPoint offSet=CGPointZero;
    CGSize boundsSize = _scroll.bounds.size;

    if (photoSize.width > boundsSize.width) {
        offSet.x=(photoSize.width-boundsSize.width)/2;
    }
    
    if (photoSize.height > boundsSize.height) {
        offSet.y=(photoSize.height-boundsSize.height)/2;
    }
    return offSet;
}
-(CGRect)getScaleFrameWithWidth:(CGFloat)width height:(CGFloat)height{
    CGRect targetImgFrame = _photoV.frame;
    
    //BOOL isRetina=[UIScreen mainScreen].scale>=2.0;
    //DLog(@"isRetina:%d",isRetina);
    CGFloat maxWidth =CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat maxHeight=CGRectGetHeight([UIScreen mainScreen].bounds);
    /*if (isRetina) {
        maxWidth=maxWidth/2;
        maxHeight=maxHeight/2;
    }*/
    CGFloat scaleHeight=0.0f;
    CGFloat scaleWidth =0.0f;
    if (height && width) {
        scaleHeight =height /(width/maxWidth);
        scaleWidth= width /(height/maxHeight);
    }
    
    //DLog(@"maxWidth:%f , maxHeight:%f",maxWidth,maxHeight);
   // DLog(@"scaleWidth:%f , scaleHeight:%f",scaleWidth,scaleHeight);

    CGSize targetSize =CGSizeMake(maxWidth, scaleHeight);
    
    if (scaleHeight >= maxHeight) {
        targetSize=CGSizeMake(scaleWidth, maxHeight);
    }
    
    targetImgFrame.size=CGSizeMake(targetSize.width, targetSize.height);
    
    targetImgFrame= [self centeredFrameForScrollView:_scroll andTargetFrame:targetImgFrame];

    return targetImgFrame;
}

- (CGRect)centeredFrameForScrollView:(UIScrollView *)scroll andTargetFrame:(CGRect)targetFrame{
    CGSize boundsSize = scroll.bounds.size;
    CGRect frameToCenter=targetFrame;

    if (frameToCenter.size.width < boundsSize.width) {
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    }
    else {
        frameToCenter.origin.x = 0;
    }

    if (frameToCenter.size.height < boundsSize.height) {
        frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
    }
    else {
        frameToCenter.origin.y = 0;
    }
    
    return frameToCenter;
}

-(void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    self.photoV.frame = [self centeredFrameForScrollView:scrollView andTargetFrame:_photoV.frame];

}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{

    return _photoV;
}



@end
